import React, { useEffect, useState, useRef, Fragment } from 'react';
import { Form, Card, Button, Table, Divider } from 'antd';
import { connect } from 'umi';
import { get as getPath } from 'object-path';
import { history } from 'umi';
import { Link }  from 'umi';
import { stringify } from 'qs';
import cn from 'classnames';
import moment from 'moment';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import PersonInfo from '@/components/PersonInfo';
import SlideTabs from '@/components/SlideTabs';
import { pathNameMap } from '@/utils/dictionary';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import { formItemLayout } from '@/components/UserForm';
import { withRoutePage } from '@/utils/enhanceUtils';
import PageRouter from '@/components/PageRouter/PageRouter';
import Pagination from '@/components/Pagination';
import { findCountry, findRecruitColor } from './part/utils';
import styles from '../RecruitMange.less';
import { XZPXX, XHXRYQ } from './part/SingaporeForm';
import { ZPXX, HXRYQ, ZPJDSZ } from './part/Form';

/**
 * 标题 接受一个Buttun做子组件 放置右边
 */
const TabsTitle = React.forwardRef(({ children, title }, ref) => (
    <div className={styles.title_edit} ref={ref}>
        <h3 className="vv-from-title" style={{ marginBottom: 0 }}>
            {title}
        </h3>
        {children}
    </div>
));
/**
 *招聘需求详情、招聘需求--用人部门详情、招聘需求--我的招聘任务详情 写在一个页面里
 * @param {query} {recruitCode companyId}
 */
const Detail = props => {
    const {
        positionManage,
        dispatch,
        form,
        route,
        form: { getFieldsValue },
        location,
        loading,
        location: {
            pathname,
            query,
            query: { recruitCode, companyId }
        }
    } = props;
    const { candidatePagination: pagination, recruitSchedule } = positionManage;
    const { authCode } = new AuthCode(route.code); // 权限code校验工具
    const [activeKey, setActiveKey] = useState('1');
    const [editZPJD, setEditZPJD] = useState(false); // 控制招聘进度表单 编辑和展示
    /** 根据定义字典判断 当前的页面 */
    const {
        isUser = false, // 用人部门必传
        isHR = false,
        code: privateCode // 临时处理我的招聘页面的权限
    } = pathNameMap.find(v => v.pathName === pathname);
    const isFirstRun = useRef(true);
    const tabs = [
        {
            label: '招聘信息',
            key: '1'
        },
        {
            label: '候选人要求',
            key: '2'
        },
        {
            label: '招聘进度设置',
            key: '3'
        },
        {
            label: '候选人',
            key: '4'
        }
    ];
    const tableColumns = [
        {
            title: '姓名',
            dataIndex: 'talentName',
            render: (text, record) => {
                const { isInterview, isApplyOffer, isWatchCandidate, candidateCode } = record;
                const params = {
                    isInterview,
                    isApplyOffer,
                    candidateCode
                };
                return (
                    <Fragment>
                        <Link
                            className={cn({
                                [styles.disabled]: !isWatchCandidate,
                                [styles.ellipsis]: true,
                                [styles.title]: true
                            })}
                            title={text}
                            to={`/personal/portal/recruit/candidate/detail?${stringify(params)}`}
                        >
                            {text}
                        </Link>
                    </Fragment>
                );
            }
        },
        {
            title: '添加候选时间',
            dataIndex: 'createTime',
            render: text => (
                <div className={styles.ellipsis} title={text}>
                    {moment(text).format('YYYY-MM-DD HH:mm')}
                </div>
            )
        },
        {
            title: '阶段',
            dataIndex: 'candidateStageValue',
            render: text => (
                <div className={styles.ellipsis} title={text}>
                    {text}
                </div>
            )
        },
        {
            title: '状态',
            dataIndex: 'candidateStateValue',
            render: text => (
                <div className={styles.ellipsis} title={text}>
                    {text}
                </div>
            )
        },
        {
            title: '候选负责人',
            dataIndex: 'candidateLeaderName',
            render: text => (
                <div className={styles.ellipsis} title={text}>
                    {text}
                </div>
            )
        }
    ];
    const getParams = () => {
        const payload = {
            recruitCode,
            isMy: isHR || isUser,
            pageNo: pagination.current,
            pageSize: pagination.pageSize
        };
        return payload;
    };
    /** 招聘进度设置按钮 */
    const getEditButton = () => {
        const isEdit = !isUser && !editZPJD;
        if (isEdit) {
            return (
                <Button
                    type="primary"
                    onClick={() => {
                        setEditZPJD(true);
                    }}
                >
                    编辑
                </Button>
            );
        }
        return null;
    };
    const handelChange = key => {
        // console.log('key==', key);
        setActiveKey(key);
    };
    const tableChange = newPagination => {
        dispatch({
            type: 'positionManage/save',
            payload: {
                candidatePagination: {
                    ...positionManage.candidatePagination,
                    ...newPagination
                }
            }
        });
    };
    // 请求整个详情页的数据
    // TODO 合并多个异步请求
    const fetchDetail = () => {
        dispatch({
            type: 'positionManage/fetchDetail',
            payload: getParams(),
            pathName: pathname
        });
    };
    /**
     * 招聘进度提交
     */
    const handleSubmit = async e => {
        e.preventDefault();
        const { schedule, leaderIds, servicePersonId, recruitSource } = getFieldsValue();
        await dispatch({
            type: 'positionManage/updateRecruit',
            payload: {
                recruitCode,
                recruitSource: recruitSource.join(),
                leaderIds,
                schedule,
                servicePersonId
            },
            dictionary: {
                pathName: pathname,
                // fetchType 查询字典 获取当前页面对应的接口
                fetchType: 'updateRecruit'
            }
        });
        fetchDetail();
        setEditZPJD(false);
    };
    const goProcessDetail = () => {
        if (isHR || isUser) {
            history.push({
                pathname: '/personal/portal/flow/mine/myApplication/detail',
                query: {
                    applicationNo: query.applicationNo
                }
            });
        } else {
            history.push({
                pathname: '/office/institutions/flowManage/fullApprovalProcess/processDetail',
                query: {
                    applicationNo: query.applicationNo,
                    linkFrom: '1'
                }
            });
        }
    };
    useEffect(() => {
        fetchDetail();
    }, []);
    useEffect(() => {
        // 更新候选人信息列表
        const fetchCandidateInfo = () => {
            dispatch({
                type: 'positionManage/fetchCandidateInfo',
                payload: getParams()
            });
        };
        if (isFirstRun.current) {
            isFirstRun.current = false;
            return;
        }
        fetchCandidateInfo();
    }, [pagination.pageSize, pagination.current]);
    const { country = 'singapore' } = findCountry(companyId);

    const getBtn = () => {
        if (!isHR) {
            return [
                <Button type="primary" onClick={goProcessDetail}>
                    查看申请流程
                </Button>
            ];
        }
        return [];
    };
    return (
        <PageHeaderWrapper>
            <PageRouter type="myrecruit" activePath="/personal/portal/recruit/task">
                <Card
                    bordered={false}
                    style={{ padding: '16px 0' }}
                    bodyStyle={{ padding: 0 }}
                    loading={
                        loading.effects['positionManage/fetchRecruitInfo'] ||
                        loading.effects['positionManage/fetchRecruitSchedule']
                    }
                >
                    <PersonInfo
                        style={{ padding: '0 16px' }}
                        name={getPath(positionManage, 'recruitInfo.recruitPost', '')}
                        num={
                            <span style={{ fontSize: '16px', color: '#FFA22D' }}>
                                {getPath(positionManage, 'recruitInfo.requireNums', '--')}人
                            </span>
                        }
                        color={findRecruitColor(recruitSchedule.schedule).color}
                        status={getPath(recruitSchedule, 'scheduleName', '')}
                        infos={[
                            {
                                label: '招聘负责',
                                value: getPath(recruitSchedule, 'leaderName', '')
                            },
                            {
                                label: '业务负责',
                                value: getPath(recruitSchedule, 'servicePersonName', '')
                            }
                        ]}
                        btns={
                            getBtn()
                            // !isHR
                            //     ? [
                            //           <Button type="primary" onClick={goProcessDetail}>
                            //               查看申请流程
                            //           </Button>
                            //       ]
                            //     : []
                        }
                    />
                    <SlideTabs
                        cardStyle={{
                            height: 'calc(100vh - 400px)',
                            marginRight: 4,
                            padding: 16
                        }}
                        tabs={tabs}
                        loading={
                            loading.effects['positionManage/fetchRecruitInfo'] ||
                            loading.effects['positionManage/fetchCandidateClaim'] ||
                            loading.effects['positionManage/fetchRecruitSchedule']
                        }
                        activeKey={activeKey}
                        onChange={key => handelChange(key)}
                    >
                        {refs => (
                            <Fragment>
                                <Form layout="horizontal" {...formItemLayout} onSubmit={handleSubmit}>
                                    <TabsTitle ref={refs[0].ref} title={tabs[0].label} />
                                    {country === 'china' ? (
                                        <ZPXX formData={positionManage.recruitInfo} form={form} />
                                    ) : (
                                        <XZPXX form={form} formData={positionManage.recruitInfo} />
                                    )}
                                    <Divider />
                                    <TabsTitle ref={refs[1].ref} title={tabs[1].label} />
                                    {country === 'china' ? (
                                        <HXRYQ formData={positionManage.candidateClaim} form={form} />
                                    ) : (
                                        <XHXRYQ form={form} formData={positionManage.candidateClaim} />
                                    )}
                                    <Divider />
                                    <TabsTitle ref={refs[2].ref} title={tabs[2].label}>
                                        <AuthComponent code={privateCode || authCode('detail:set')}>
                                            {getEditButton()}
                                        </AuthComponent>
                                    </TabsTitle>
                                    <ZPJDSZ
                                        location={location}
                                        form={form}
                                        query={query}
                                        formData={positionManage.recruitSchedule}
                                        editZPJD={editZPJD}
                                        setEditZPJD={setEditZPJD}
                                    ></ZPJDSZ>
                                </Form>
                                <Divider />
                                <TabsTitle ref={refs[3].ref} title={tabs[3].label} />
                                <Table
                                    columns={tableColumns}
                                    style={{ marginTop: '12px' }}
                                    dataSource={positionManage.candidateInfo}
                                    onChange={tableChange}
                                    loading={loading.effects['positionManage/fetchCandidateInfo']}
                                    bordered={false}
                                    rowKey="id"
                                    scroll={{ x: 'max-content' }}
                                    pagination={false}
                                />
                                <Pagination {...pagination} onChange={tableChange} />
                            </Fragment>
                        )}
                    </SlideTabs>
                </Card>
            </PageRouter>
        </PageHeaderWrapper>
    );
};

const mapStateToProps = ({ positionManage, loading }) => ({
    positionManage,
    loading
});
export default withRoutePage(connect(mapStateToProps)(Form.create()(Detail)));
